import click
import os
import platform
import sys
from collections import OrderedDict

import json
import pandas as pd
from common.database import SessionLocal
from datetime import datetime, time

from app.monitor_metrics.models.prom_alarm_record import PromAlarmRecord
from app.monitor_metrics.models.prom_alarm_rule import PromAlarmRule
from app.monitor_metrics.models.prom_alarm_metrics import PromAlarmMetrics
from app.monitor_metrics.models.prom_host_info import PromHostInfo
from app.monitor_metrics.models.prom_host_group import PromHostGroup


from core.logger import logger


class AlarmClick(object):
    def __init__(self):
       self.session = SessionLocal()


    def __del__(self):
        self.session.close()


    def export_alarm_record(self, start, end):
        """
        导出告警记录，用作服务质量报告
        """
        start_date = datetime.strptime(start, "%Y-%m-%d")
        end_date = datetime.strptime(end, "%Y-%m-%d")
        record_infos = PromAlarmRecord.get_object_info_for_time(self.session, start_date, end_date)
        if not record_infos:
            logger.error("get alarm record info failed")
            return False

        export_data = []
        for record_info in record_infos:
            if not record_info["comment"]:
                continue

            metrics_comment = ""
            rule_object = PromAlarmRule.get_object_by_name(self.session, record_info["name"])
            if rule_object:
                rule_info  = PromAlarmRule.get_object_info_by_name(self.session, record_info["name"])
                metrics_info = PromAlarmMetrics.get_object_info_by_uuid(self.session, rule_info["alarm_metrics_uuid"])
                metrics_comment = metrics_info["comment"]
            self_healing = "故障自愈" if "自愈" in record_info["comment"] else "手动处理"
            data = {
                "告警规则名称": record_info["name"],
                "告警归类": record_info["classes"],
                "指标归类": metrics_comment,
                "告警处理": self_healing,
                "告警状态": record_info["status"],
                "告警级别": record_info["labels"]["i_level"],
                "告警次数": record_info["notice_count"],
                "通知详情": record_info["annotations"],
                "开始时间": record_info["starts_at"],
                "结束时间": record_info["ends_at"],
                "备注说明": record_info["comment"],
            }
            export_data.append(data)
            logger.info(f"export alarm record:{record_info['fingerprint']} success")

        df = pd.DataFrame(export_data)
        df.to_excel(f"指标告警记录.xlsx", index=False)
        logger.info("export all alarm record success")
        return True



    def export_host_info(self):
        """
        导出主机信息
        """
        host_infos = PromHostInfo.get_all_host_info(self.session)

        export_data = []
        for host_info in host_infos:
            host_group_info = PromHostGroup.get_object_info_by_light(self.session, host_info["host_group_uuid"])
            data = {
                "部门名称": host_group_info["department"],
                "组名": host_group_info["name"],
                "主机名": host_info["name"],
                "ip地址": host_info["ip"],
                "状态": host_info["state"],
                "说明": host_info["comment"]
            }
            export_data.append(data)
            logger.info(f"export host info:{host_info['name']} success")

        df = pd.DataFrame(export_data)
        df.to_excel(f"服务器信息.xlsx", index=False)
        logger.info("export all host info success")
        return True



    def export_alarm_rule(self):
        """
        导出告警规则，用作公司内部审计
        """
        field_info = {"all": None}
        order_info = {"classes": "asc", "name": "asc"}
        result = PromAlarmRule.filter_by_field_search(self.session, 1, 100000, field_info, order_info)
        if not result:
            logger.warning(f"get alarm rule search, result is null")
            return False, None
        
        export_data = []
        for item in result["items"]:
            metrics_info = PromAlarmMetrics.get_object_info_by_uuid(self.session, item["alarm_metrics_uuid"])
            data = {
                "规则名称": item["name"],
                "规则分类": item["classes"],
                "规则类型": item["type"],
                "规则状态": item["state"],
                "监控目标": item["target"],
                "指标名称": metrics_info["name"],
                "运算符": item["operator"],
                "告警阀值": item["value"],
                "持续分钟": item["duration"],
                "告警级别": item["level"],
                "告警阀值": item["value"],
            }
            export_data.append(data)

        # for item in result["items"]:
        #     metrics_info = PromAlarmMetrics.get_object_info_by_uuid(self.session, item["alarm_metrics_uuid"])
        #     item["alarm_metrics_comment"] = metrics_info["comment"]

        df = pd.DataFrame(export_data)
        df.to_excel(f"告警规则.xlsx", index=False)
        logger.info("export alarm rule success")
        return True
    
    def update_alarm_rule(self):
        field_info = {"all": ""}
        order_info = {"classes": "asc", "name": "asc"}
        result = PromAlarmRule.filter_by_field_search(self.session, 1, 100000, field_info, order_info)
        if not result:
            logger.warning(f"get alarm rule search, result is null")
            return False
        
        # 过滤内部标签
        for rule in result["items"]:
            if rule["labels"]["i_level"] == "warning":
                rule["labels"]["i_level"] = "major"
            elif rule["labels"]["i_level"] == "comment":
                rule["labels"]["i_level"] = "warning"
            elif rule["labels"]["i_level"] == "info":
                rule["labels"]["i_level"] = "warning"
            else:
                continue
            
            data = {
                "uuid": rule["uuid"],
                "labels": rule["labels"]
            }

            result = PromAlarmRule.update(self.session, data)
            if not result:
                logger.error(f"update alarm rule to database failed")
                return False
        
        


def main():
    alarm_click = AlarmClick()

    # # 导出告警记录
    # start = "2022-01-01"
    # end = "2022-08-31"
    # alarm_click.export_alarm_record(start, end)

    # 导出告警规则
    # alarm_click.export_alarm_rule()

    # 导出主机信息
    # alarm_click.export_host_info()
    
    alarm_click.update_alarm_rule()


if __name__ == "__main__":
    main()
